//
//  ZYCache.swift
//  ZYUICommon
//
//  Created by Yi Zhou on 2025/1/4.
//
//

import YYCache

public class ZYCache: NSObject {
    
    private override init() {}
    
    public static let shared = ZYCache()
    
    private let cache = YYCache(name: "https://gitee.com/zhou-yi-111/zyuicommon.git")
    
    /// 配置存储属性
    /// - Parameters:
    ///   - memoryObjectLimit: 内存最多存储的对象个数
    ///   - memoryLimit: 内存最大容量
    ///   - diskObjectLimit: 磁盘最多存储的对象个数
    ///   - diskLimit: 磁盘最大容量
    public func config(_ memoryObjectLimit: Int?, _ memoryLimit: Int?, _ diskObjectLimit: Int?, _ diskLimit: Int?) {
        if let mobject = memoryObjectLimit {
            cache?.memoryCache.countLimit = UInt(mobject)
        }
        if let memory = memoryLimit {
            cache?.memoryCache.costLimit = UInt(memory)
        }
        if let dobject = diskObjectLimit {
            cache?.diskCache.countLimit = UInt(dobject)
        }
        if let disk = diskLimit {
            cache?.diskCache.costLimit = UInt(disk)
        }
    }
    
    /// 存储对象
    /// - Parameters:
    ///   - key: key description
    ///   - value: value description
    public func cacheObject<T: Codable>(_ key: String, _ value: T) {
        if let data = try? JSONEncoder().encode(value) {
            cache?.setObject(data as NSCoding, forKey: key)
            debugPrint("ZYUICommon/ZYCache/存储成功：key=\(key)")
        }
    }
    
    /// 取出对象
    /// - Parameters:
    ///   - key: key description
    ///   - type: type description
    /// - Returns: description
    public func readObject<T: Codable>(forKey key: String, as type: T.Type) -> T? {
        if let data = cache?.object(forKey: key) as? Data,
           let object = try? JSONDecoder().decode(type, from: data) {
            return object
        }
        return nil
    }
    
    /// 移除对象
    /// - Parameter key: key description
    public func removeObject(_ key: String) {
        cache?.removeObject(forKey: key)
    }
    
    /// 清空所有存储对象
    public func clearCache() {
        cache?.removeAllObjects()
    }
}
